<?php
	/**
	 * Created by PhpStorm.
	 * User: mybook-lhp
	 * Date: 18/5/23
	 * Time: 下午2:04
	 */

	namespace app\payment\logic;

	use Omnipay\Omnipay;
	use think\Log;

	class PayWechat extends PayBase
	{


		/**
		 * 发起支付
		 * @param $body    string 支付文本名称
		 * @param $out_trade_no    int 支付单号
		 * @param $total_fee    int 支付金额
		 * @param $open_id    string 用户OPenID
		 * @return mixed
		 */
		static public function miniapp($pay_data)
		{
			$res = static::checkData($pay_data);
			if ($res !== 'ok')
			{
				return $res;
			}
			//获取配置
			$config = self::getConfig($pay_data['pay_type']);
			if (!$config)
			{
				return '微信配置不存在！';
			}
			//gateways: WechatPay_App, WechatPay_Native, WechatPay_Js, WechatPay_Pos, WechatPay_Mweb
			$gateway = Omnipay::create('WechatPay_Js');
			$gateway->setAppId($config['appid']);
			$gateway->setMchId($config['mch_id']);
			$gateway->setApiKey($config['mch_key']);

			$order = [
				'body'             => $pay_data['pay_name'],
				'out_trade_no'     => $pay_data['pay_sn'],
				'total_fee'        => floor($pay_data['amoun'] * 100), //=0.01
				'spbill_create_ip' => gethostbyname($_SERVER['SERVER_NAME']),
				'fee_type'         => 'CNY',
				'open_id'          => $pay_data['open_id'],
			];

			if (isset($pay_data['notify_url']) && $pay_data['notify_url'] != '')
			{
				$order['notify_url'] = request()->domain() . $pay_data['notify_url'];
			} else
			{
				$order['notify_url'] = request()->domain().'/payment/callback/wxcallback'; //回调地址
			}
			Log::wechat(json_encode($order));
			/**
			 * @var Omnipay\WechatPay\Message\CreateOrderRequest $request
			 * @var Omnipay\WechatPay\Message\CreateOrderResponse $response
			 */
			$request = $gateway->purchase($order);
			$response = $request->send();
			if ($response->isSuccessful())
			{
				return $response->getJsOrderData();
			}
			$resp = $response->getData();
			if (isset($resp['return_code']) && $resp['return_code'] == 'FAIL')
			{
				return ['weixin_respone' => $resp, 'order' => $order, 'pay_data' => $pay_data];
			}

			/**
			 * dump([
			 * 'config' => $config,
			 * 'order'  => $order,
			 * $response->isSuccessful(),//available methods
			 * $response->getData(), //For debug
			 * $response->getAppOrderData(), //For WechatPay_App
			 * $response->getJsOrderData(), //For WechatPay_Js
			 * $response->getCodeUrl(), //For Native Trade Type
			 * ]);*/
		}

		/**
		 * 退款
		 * @param $pay_data
		 * @return array|string
		 */
		static public function refund($pay_data)
		{

			//获取配置
			$config = self::getConfig($pay_data['pay_type']);
			if (!$config)
			{
				return '微信配置不存在！';
			}
			//gateways: WechatPay_App, WechatPay_Native, WechatPay_Js, WechatPay_Pos, WechatPay_Mweb
			$gateway = Omnipay::create('WechatPay_Js');
			$gateway->setAppId($config['appid']);
			$gateway->setMchId($config['mch_id']);
			$gateway->setApiKey($config['mch_key']);
			if (file_exists(Env::get('root_path') . 'cert/apiclient_cert.pem'))
			{
				$gateway->setCertPath(Env::get('root_path') . 'cert/apiclient_cert.pem');
			} else
			{
				return ['error' => 'CERTIFICATE 证书不存在', 'path' => Env::get('root_path') . 'cert/apiclient_cert.pem'];
			}
			if (file_exists(Env::get('root_path') . 'cert/apiclient_key.pem'))
			{
				$gateway->setKeyPath(Env::get('root_path') . 'cert/apiclient_key.pem');
			} else
			{
				return ['error' => 'PRIVATE 证书不存在', 'path' => Env::get('root_path') . 'cert/apiclient_key.pem'];

			}
			if (isset($pay_data['notify_url']) && $pay_data['notify_url'] != '')
			{
				$order['notify_url'] = request()->domain() . $pay_data['notify_url'];
			} else
			{
				$pay_data['notify_url'] = request()->domain() . '/api.php/paygateway/callback/wechatpay';
			}
			$refund = [
				'transaction_id' => $pay_data['transaction_id'], // 微信生成的订单
				'out_trade_no'   => $pay_data['pay_sn'], //商家自己的订单
				'out_refund_no'  => $pay_data['out_refund_no'],//退款订单
				'total_fee'      => $pay_data['total_fee'] * 100, //=0.01原始总支付金额
				'refund_fee'     => $pay_data['refund_fee'] * 100, //=0.01退还支付金额
				'notify_url'     => $pay_data['notify_url'], //回调
			];

			$response = $gateway->refund($refund)->send();
			Log::refund(json_encode($pay_data));
			if ($response->isSuccessful())
			{

				return $response->getData();
			}
			return ['weixin_respone' => $response->getData(), '$refund' => $refund, 'weixin_config' => $config];

		}


	}